var regeneratorRuntime = require("../../../../lib/js/runtime-module.js")
import Config from '../../../../utils/config2.js'
import cardConfig from '../../../../config.js'
import util from '../../../../utils/util'
import formatDate from '../../../../utils/util2.js'
import Serv from './gameIndexServ';
var sensorsdata_conf = require("../../../../utils/sensorsdata_conf.js")
var WxParse = require('../../../../wxParse/wxParse.js');

var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    checkUserInfo:{},//判断当前用户是否可以抽奖
    isAddUserSuccess:false,//判断是否已经添加用户成功
    showRule:true,
    background: ['demo-text-1', 'demo-text-2', 'demo-text-3'],
    iconAdd:"https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/icon-add.png",
    defualtHeard:'https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/card/card_defaultImg.png',
    gameActivityId:'',
    activityDetail:{},//活动详情
    userData:{},//用户活动数据
    gamePrizeList:[],//活动中奖信息
    assistanceList:[],//助力列表
     //倒数数据
     coutDownDate: {
      day: '00',
      hour: '00',
      minite: '00',
      second: '00'
    },
    //倒计时控件
    timer: '',
    loadDataTime:'',
    timerDistance:'',
    //活动状态  0未开始  1已开始  2已结束   3待定
    activityStatus:'',
    // timerDistance:'',
    activityStatusObj:{0:'开始',1:'结束',2:'已结束',3:'待定'},
    sharePamars:'',
    content:'',
    consultantInfo:[],
    dialogStatus:false,
    showHelp:false,
    gameHighSetData:{},
    actionType:"",
    helpDialog:false,
    helpPamars:{},
    isHelp:false,
    relationMap:{},

  },
  //预加载海报图片
  preload: function () {
    let {gameHighSetData}=this.data;
    var userInfoData = wx.getStorageSync('userInfoData')
    var userInfo = wx.getStorageSync('userInfo')
    let bg = [`${(gameHighSetData && gameHighSetData.posterImgUrl) ? gameHighSetData.posterImgUrl:''}`, userInfoData.headImgUrl || userInfo.avatarUrl];
    // //debugger
    formatDate.imgPreLoad(bg, (preLoadImg) => {
      wx.setStorageSync('preLoadImg', preLoadImg)
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(!app.globalData.isAddUserSuccess){
      wx.hideShareMenu();
    }
    let {gameActivityId,type,routerType,actionType,helpPamars} =options
    if(routerType=='login'){
      let preInfo = options.options
      
      preInfo = JSON.parse(preInfo)
      console.log(JSON.parse(options.options))
      let {gameActivityId,helpPamars} = preInfo
      if(preInfo.helpPamars){
        preInfo.helpPamars = JSON.parse(preInfo.helpPamars)

        this.setData({
          helpPamars:preInfo.helpPamars,
          helpDialog:true,
          gameActivityId:preInfo.helpPamars.gameActivityId

        })
      }else{
        this.setData({
          gameActivityId:gameActivityId
        })
      }
    }
    if(gameActivityId){
      this.setData({
        gameActivityId:gameActivityId
      })
    }
    if(actionType=='help'){
      helpPamars = JSON.parse(helpPamars)
      let status = helpPamars.mobilePhone == wx.getStorageSync('phoneNo')?false:true
      this.setData({
        helpDialog:status,
        helpPamars,
        gameActivityId:helpPamars.gameActivityId
      })
    }
    // this.setData({
    //   gameActivityId:gameActivityId,
    //   type
    // })
  },

  
  //活动详情
  async queryDetail(pamars){
    let nowdata = new Date().getTime();

    let {success,result,timestamp} = await Serv.getDetail(pamars)
    if(success){
      let time = timestamp
      let nowdata2 = new Date().getTime();
      let wucha = nowdata2 - nowdata
      WxParse.wxParse('content', 'html', result.ruleDesc, this, 5)

      this.setData({
        activityDetail:result,
        timerDistance: nowdata2 - (time+wucha)
      })
      clearTimeout(this.data.timer);
      this.countDown()
    }
  },
  //用户活动数据
  async userDetail(pamars){
    // let nowdata = new Date().getTime();
    let {success,result} = await Serv.userDetailServ(pamars)
    if(success){
      let {assistanceList} = result
      assistanceList = assistanceList || []
      // console.log(assistanceList.length)
      let length = assistanceList.length
      if(length<=3){
        let obj = {}
        let i
        for( i=3;i>length;i--){
          assistanceList.push(obj)
        }
      }else{
        assistanceList = assistanceList.slice(0,3)
      }
      this.setData({
        userData:result,
        assistanceList
      })      
    }
  },
//活动中奖信息
  async getGamePrizeList(){
    let params = {gameActivityId:this.data.gameActivityId || wx.getStorageSync('gameInfo').gameActivityId}
    let {success,result,message} = await Serv.getGamePrizeList(params)
    if(success){
      this.setData({
        gamePrizeList:result.records
      })
    }else{
      wx.showToast({
        title:message,
        icon:'none'
      })
    }
    
  },
  async addUser(){
    let that = this;
    if(app.globalData.cityData){
      let detailPamars = {
        gameActivityId:this.data.gameActivityId,
        mobilePhone:wx.getStorageSync('phoneNo')
      }
      app.addUser(this.data.gameActivityId,()=>{
       
        that.setData({
          isAddUserSuccess: true
        });
        that.checkUser();
        this.userDetail(detailPamars)
      })
    }
    

  },
  closeModel(){
    this.setData({
      dialogStatus:!this.data.dialogStatus
    })
  },
  closeHelp(){
    this.setData({
      helpDialog:!this.data.helpDialog
    })
  },
  async assistance(){
    // let {activityInfo} = this.data
    let userData = wx.getStorageSync('userData')
    let phoneNo = wx.getStorageSync('phoneNo');
    let parmas = {
      parentMobilePhone:this.data.helpPamars.mobilePhone,
      mobilePhone:phoneNo,
      gameActivityId:this.data.gameActivityId
    }
    if(!app.globalData.cityData){
      app.resetLocation(()=>{
        this.addUser();
     })
     return false;
    }
    let {success,message} = await Serv.assistanceServ(parmas)

    if(success){
      wx.showToast({
        title:'助力成功',
        icon:'success'
      })
      this.setData({
        isHelp:!this.data.isHelp
      })
    }else{
      wx.showToast({
        title:message,
        icon:'none'
      })
    }
  },
  
  /**
   * 倒数
   */
  countDown() {
    let that = this;
    let {startTime,endTime} = that.data.activityDetail
    // let startTime = '2020-03-17 13:51:04'
    // let endTime = '2020-03-19 11:50:00'
    var selStartTime = new Date(startTime.replace(/-/g, '/')).getTime();
    var selEndTime = new Date(endTime.replace(/-/g, '/')).getTime();

    var nowTime = new Date().getTime() - this.data.timerDistance;

    var start_total_second = selStartTime-nowTime;
    var end_total_second = selEndTime-nowTime

    // let nowShowTime = that.data.coutDownDate
    // var nextTime = ''
    if(that.data.timer){
      clearTimeout(that.data.timer);
    }
    // console.log('start_total_second',start_total_second)
    // console.log('end_total_second',end_total_second)
    if (start_total_second > 0) {
      //未开始
      if (that.data.activityStatus!=0 || !that.data.activityStatus) {
        that.setData({
          activityStatus: 0
        });
      }
      that.setData({
        coutDownDate: that.dateformat(start_total_second, that)
      });

    } else if (end_total_second > 0) {
      //已开始
      if (that.data.activityStatus != 1){
        that.setData({
          activityStatus: 1
        });
      }
      that.setData({
        coutDownDate: that.dateformat(end_total_second, that)
      });
    } else {
      //已结束
      if (that.data.activityStatus!=2){
        that.setData({
          activityStatus: 2
        });
      }
      that.setData({
        coutDownDate: that.dateformat(0, that)
      });
      clearTimeout(that.data.timer);
    }
    if (this.data.activityStatus!=2) {
      that.data.timer = setTimeout(function () {
        that.countDown(that);
      }, 500);
    }

  },
  // 时间格式化输出，每1s都会调用一次
  dateformat(micro_second, that) {
    // 总秒数
    var second = Math.ceil(micro_second / 1000);
    // 天数
    var day = Math.floor(second / 3600 / 24);
    var dayStr = day.toString();
    if (day <= 0) {
      dayStr = '0'
    }
    // 小时
    var hr = Math.floor(second / 3600 % 24);
    var hrStr = hr.toString();
    if (hrStr.length == 1) hrStr = '0' + hrStr;
    if (hr <= 0) {
      hrStr = '00'
    }
    // 分钟
    var min = Math.floor(second / 60 % 60);
    var minStr = min.toString();
    if (minStr.length == 1) minStr = '0' + minStr;
    if (min <= 0) {
      minStr = '00'
    }
    // 秒
    var sec = Math.floor(second % 60);
    var secStr = sec.toString();
    if (secStr.length == 1) secStr = '0' + secStr;
    if (sec <= 0) {
      secStr = '00';
    }
    var tempDate = {
      day: dayStr,
      hour: hrStr,
      minite: minStr,
      second: secStr
    }

    return tempDate
  },
   /**
   * 定时器加载数据
   */
//   startReportHeart(pamars) {
//     let that = this;
//     this.data.loadDataTime = setTimeout(function () {
//       this.queryDetail(pamars)
//        that.startReportHeart()
//     }, 1000)
//     
//   },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(this.data.gameActivityId){
      let detailPamars = {
        gameActivityId:this.data.gameActivityId,
        mobilePhone:wx.getStorageSync('phoneNo')
      }
      this.queryDetail(detailPamars)
      this.getGamePrizeList()
      this.getHighSetData();
      if(!app.globalData.cityData){
        app.resetLocation(()=>{
          this.addUser();
       })
      }else{
        this.addUser();
      }
    }
  },

  showRule(){
    this.setData({
      showRule:!this.data.showRule
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    sensorsdata_conf.server_url = `${cardConfig.config.pageDomain}applet/visitLog/create`
    sensorsdata_conf.batch_send.send_timeout = 6000
    app.globalData.sensors.setPara(sensorsdata_conf);
    clearTimeout(this.data.timer);
    clearTimeout(this.data.loadDataTime)
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    sensorsdata_conf.server_url = `${cardConfig.config.pageDomain}applet/visitLog/create`
    sensorsdata_conf.batch_send.send_timeout = 6000
    app.globalData.sensors.setPara(sensorsdata_conf);
    clearTimeout(this.data.timer);
    clearTimeout(this.data.loadDataTime)
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  async checkUser(){
    let userData = wx.getStorageSync("userData");
    let params = {
      gameActivityId: this.data.gameActivityId,
      mobilePhone: userData.mobile
    }
    let { success,result, message } = await Serv.checkUserServ(params);
    let checkUserInfo = {
      checkUserStatus: success,
      message: message
    };
    this.setData({
      checkUserInfo: checkUserInfo
    });
  },
  // contact(){

  // },
  getConsultant:async function(){
    let that = this
    let {projectId,type,dialogStatus} = this.data.activityDetail
    wx.showLoading()
    if(projectId){
      this.goldConsultants(projectId)
    }else{
      this.projectQueryList()
    }
  },
  //查询活动项目列表
  async projectQueryList(){
    let {city,cityadcode,province,provinceCode} = app.globalData.cityData

    let params = {
      cityCode:cityadcode
    }
    let {success,rows} = await Serv.queryList(params)
    if(success){
      this.goldConsultants(rows[0].outerId)
    }
  },

  goldConsultants(projectId){
    let that = this
    let customerPhone = wx.getStorageSync('phoneNo')
    let {type,dialogStatus} = this.data.activityDetail

    wx.request({
      url: `${Config.dataCenter}huiSales/ranking/${projectId}/${customerPhone}/goldConsultants3`,//`http://10.73.159.79:8097/huiSales/ranking/${data.outerId}/projectSalesTop`,
      data:{},
      header: {
        'content-type': 'application/json',
        'token':wx.getStorageSync('authName')
      },
      success:function(res){
        // console.log(res)
        let mobileArr = []
        let {data} = res.data
        if(data.length>0){
          // type: 
          if(type==1){
            let {eid} = data[0]
            that.massage(eid,'game')
          }else{
            that.setData({
              consultantInfo:data,
              dialogStatus:!dialogStatus
            });
          }
          
        }
        wx.hideLoading()

      },
      fail:function(err){
        wx.showToast({
          title:err.message
        })
      }
    })
  },
  toCard(e){
    var ctx = this;
    var eId = e.currentTarget.dataset.eid;
    if (!ctx.data.relationMap[eId]) { //没有关系才进行绑定
      util.addRelation(eId, wx.getStorageSync('cusmallToken'), ctx.data.source);
    }
    wx.setStorageSync("eId", eId); //员工id
    // wx.switchTab({
    //   url: '/pages/mycard/card?eId=' + eId
    // });
    wx.navigateTo({
      url: '/pages/mycard/card?eId=' + eId
    })
    
  },
  callphone(e){
    console.log(e)
    let phone = e.currentTarget.dataset.phone
    wx.makePhoneCall({
      phoneNumber:phone
    })
    e.currentTarget.dataset.phone
  },
  massage: function (e,type) {
    console.log(cardConfig.config.messageTemplateId)
    let eId1
    if(type == 'game'){
      eId1 = e
    }else{
      eId1 = e.currentTarget.dataset.eid
    }
    // let eId1 = eid || e
    // var eId2 = wx.getStorageSync('eId');
    // let eId = eId1 ? eId1 : eId2
    // this.setData({
    //   isNewsTip: false,
    //   card_detail_noread: 0
    // })
    app.subscribeMessage(()=>{
      wx.navigateTo({
        url: "/subPackages/pages/chat_detail/chat_detail?eId=" + eId1
      });
    },cardConfig.config.messageTemplateId);
    wx.setStorageSync("has_readmsg_" + eId1, true);
    // debugger
  },
  changeDialog(){
    this.setData({
      dialogStatus:!this.data.dialogStatus
    })
  },

 
  //邀请朋友助力
  async inviteF(){
    let userInfo = wx.getStorageSync('userInfo')
    let userData = wx.getStorageSync('userData')
    let pamars = {
      nickname:userInfo.nickName,
      mobilePhone:userData.mobile,
      gameActivityId:this.data.gameActivityId
    }
    
    let {success,message} = await Serv.inviteCountServ(pamars)
    if(success){
      // pamars = JSON.stringify(pamars)

      // wx.navigateTo({
      //   url:`/subPackages3/pages/gameManage/gameResult/gameResult?pamars=${pamars}`
      // })
    }else{
      wx.showToast({
        title:message,
        icon:'none'
      })
    }
  },
  //中奖信息
  toList(e){
    let {type,id,title,isshow} = e.currentTarget.dataset
    // debugger
    wx.navigateTo({
      url:`/subPackages3/pages/gameManage/gameList/gameList?type=${type}&gameActivityId=${id}&title=${title}&isShow=${isshow}`
    })
  },

  //找房
  toHouseList(){
    let {city,cityadcode,province,provinceCode} = app.globalData.cityData
    // wx.navigateTo({
    //   url:`/subPackages3/pages/houseList/houseList`
    // })
    let { activityDetail } = this.data;
    if(activityDetail.type==1){
    sensorsdata_conf.server_url =`${Config.host}app/dataAnalysis/create`
    sensorsdata_conf.batch_send.send_timeout = 0
    app.globalData.sensors.setPara(sensorsdata_conf);
    app.globalData.sensors.track('gameEvent', {gameActivityId: activityDetail.gameActivityId,productId:activityDetail.productId});
    wx.navigateTo({
      url:`/subPackages/pages/buildingDetail/buildingDetail?productId=${activityDetail.productId || ''}`
    })
      return;
    }
    wx.navigateTo({
      url:`/subPackages3/pages/queryHouse/queryHouse?gameActivityId=${this.data.gameActivityId}&productId=${this.data.activityDetail.productId || ''}`
    })
  },
  //去抽奖
  toDraw(){
    let checkUserInfo = this.data.checkUserInfo;
    if (checkUserInfo.checkUserStatus){
      wx.navigateTo({
        url: `/subPackages3/pages/gameManage/game/game?gameActivityId=${this.data.gameActivityId}`
      })
    }else{
      wx.showToast({
        title: checkUserInfo.message,
        icon: 'none'
      })
    }
  },
  userNoGame(){
    let checkUserInfo = this.data.checkUserInfo;
    if (!checkUserInfo.checkUserStatus) {
      wx.showToast({
        title: checkUserInfo.message,
        icon: 'none'
      });
    }
  },
  showHelp(){
    this.setData({
      showHelp: !this.data.showHelp
    })
  },
  //获取高级设置的数据
  async getHighSetData() {
    let that = this;
    let params = {
      gameActivityId: that.data.gameActivityId
    };
    let { success, result } = await Serv.getHighSetData(params);
    console.log(result);
    if (success) {
      if (result) {
        if(result.allowSharing==0){
          wx.hideShareMenu()
        }
        that.setData({
          gameHighSetData: result
        });
        //分享海报预加载
        that.preload();
      }
    }
  },
  // 分享海报
  toPoster(){
    let gameHighSetData = this.data.gameHighSetData;
    console.log("生成助力海报");
    wx.navigateTo({
      url: `/subPackages/pages/housePoster/housePoster?gameActivityId=${this.data.gameActivityId}&type=4&actionType=${gameHighSetData.assistedOpening == 1?'help':''}&pageName=gameIndex&posterPic=${(gameHighSetData && gameHighSetData.posterImgUrl && gameHighSetData.posterImgUrl != '') ? gameHighSetData.posterImgUrl:''}`
    })
  },
  gotoGame(){
    this.setData({
      helpDialog:false
    })
  },
  //去看看其他活动吧
  toProduct(){
    let {productId} = this.data.activityDetail
    if(productId){
      wx.navigateTo({
        url:`/subPackages/pages/buildingDetail/buildingDetail?productId=${productId}`
      })
    }else{
      wx.switchTab({
        url:`/pages/index/index`
      })
    }
  },
  gotoBuilding(e){
    let projectId = e.currentTarget.dataset.projectid
    wx.navigateTo({
      url:`/subPackages/pages/buildingDetail/buildingDetail?projectId=${projectId || ''}`
    })
  },
 /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var _this =this
    let userInfo = wx.getStorageSync('userInfo')
    let userData = wx.getStorageSync('userData')
    let {gameHighSetData} = this.data
    let helpPamars = {
      nickname:userInfo.nickName,
      mobilePhone:userData.mobile,
      gameActivityId:this.data.gameActivityId
    }
    helpPamars = JSON.stringify(helpPamars)

    let shareObj = {
      title: gameHighSetData.sharingTitle,
      imageUrl: gameHighSetData.sharingImgUrl
    }
    if (app.globalData.isAddUserSuccess) {
    wx.showShareMenu();
    this.inviteF()
    if(gameHighSetData.allowSharing==1&&_this.data.isCheckActivityUser==false){ //可分享但不是业主
      shareObj.path = `/subPackages3/pages/gameManage/gameTransferStation/gameTransferStation?gameActivityId=${this.data.gameActivityId}`
    }
    else if(gameHighSetData.allowSharing==1&&gameHighSetData.assistedOpening==0){//可分享不可助力，分享当前活动而不是助力
      shareObj.path = `/subPackages3/pages/gameManage/gameTransferStation/gameTransferStation?gameActivityId=${this.data.gameActivityId}`
      // shareObj = {
      //   title: gameHighSetData.sharingTitle,
      //   path: `/subPackages3/pages/gameManage/gameTransferStation/gameTransferStation?gameActivityId=${this.data.gameActivityId}`,
      //   imageUrl: gameHighSetData.sharingImgUrl
      // }
    }else{
      shareObj.path = `/subPackages3/pages/gameManage/gameTransferStation/gameTransferStation?helpPamars=${helpPamars}&actionType=help`

      // shareObj = {
      //   title: gameHighSetData.sharingTitle,
      //   path: `/subPackages3/pages/gameManage/gameTransferStation/gameTransferStation?helpPamars=${helpPamars}&actionType=help`,
      //   imageUrl: gameHighSetData.sharingImgUrl
      // }
    }
    //  wx.navigateTo({
    //     url:`/subPackages3/pages/gameManage/gameTransferStation/gameTransferStation?gameActivityId=${this.data.gameActivityId}`
    //   })
    // debugger
      // wx.navigateTo({
      //   url:`/subPackages3/pages/gameManage/gameTransferStation/gameTransferStation?helpPamars=${helpPamars}&actionType=help`
      // })
      _this.setData({
        showHelp:false
      })
      console.log(shareObj)
    // return {
    //   title: '邀请好友助力',
    //   path: `/subPackages3/pages/gameManage/gameTransferStation/gameTransferStation?helpPamars=${helpPamars}&actionType=help`,
    //   imageUrl: this.data.activityDetail.titleImgUrl
    // }
    }else{
      shareObj.path = `/subPackages3/pages/gameManage/gameTransferStation/gameTransferStation?gameActivityId=${this.data.gameActivityId}`
    }
    return shareObj
  }
})